package fr.insee.rome.io.mots;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Set;

import fr.insee.rome.factory.RomeFactory;
import fr.insee.rome.string.norm.RomeNormalizer;

public class CsvMotsBuilder {

	private RomeNormalizer normalizer;
	private Mots elements;
	
	public CsvMotsBuilder(){
		normalizer = RomeFactory.getNormalizer();
		elements = RomeFactory.getMots();
	}
	
	public void build(String input, String output){
		
		try {
			InputStream stream = new FileInputStream(input);
			Reader reader = new InputStreamReader(stream);
			BufferedReader buffer = new BufferedReader(reader);
			
			String line = null;
			while((line = buffer.readLine()) != null){
				
				String[] tokens = line.split("=");
				Set<String> mots = normalizer.normaliser(tokens[1]);
				for (String mot : mots) {
					elements.add(mot, tokens[0]);
					System.out.println(mot);
				}
				tokens = null;
			}
			
			buffer.close();
			reader.close();
			stream.close();
			
			buffer = null;
			reader = null;
			stream = null;
			
			FileWriter writer = new FileWriter(output);
			
			for (String  element : elements) {
				
				StringBuffer sequence = new StringBuffer(); 
				sequence.append(element + "=");
				for (String code : elements.get(element)) {
					sequence.append(code + ",");
				}
				sequence.setCharAt(sequence.length() - 1, (char)10);
				writer.append(sequence);
			}		
			writer.close();
			writer = null;
		}
		catch (IOException e) {
			e.printStackTrace();
		}
	}
}
